<template>
  <div>
    <header class="header">
      <el-button @click="$router.push('/teacher/dashboard')" icon="left" type="text" class="back-button">
        <img src="@/assets/svgs/left.svg" alt="Back" />
      </el-button>
      <span class="title">AIGC智能作业</span>
      <div class="header-right">
        <el-button @click="$router.push('/teacher/assignment/assign_homework')" type="text"
          class="assign-button">布置作业</el-button>
      </div>
    </header>
    <div class="homework-card-list">
      <div v-for="homework in homeworks" :key="homework.id" class="homework-card" @click="handleCardClick(homework.id)"
        style="cursor: pointer">
        <div>
          <div class="homework-title">{{ homework.title }}</div>
          <div class="homework-status">状态：{{ homework.status }}</div>
          <div class="homework-dates">
            <div>发布时间：{{ formatDate(homework.publishTime) }} 截止时间：{{ formatDate(homework.dueTime) }}</div>
          </div>
        </div>
        <div class="homework-submission">
          <div class="submission-count">
            <div class="submission-number">{{ homework.submittedCount }}/{{ homework.totalCount }}</div>
            <div class="submission-label">提交人数</div>
          </div>
          <div class="submission-score">
            <div class="score-number">{{ homework.score }}</div>
            <div class="score-label">分数</div>
          </div>
        </div>
      </div>
    </div>
    <FloatingBubble v-if="showBubble"/>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus';
import { useCounterStore } from "@/stores/counter";
import { gethomeworkService } from '@/api/homework';
import FloatingBubble from '@/components/FloatingBubble.vue'

const route = useRoute();
const router = useRouter();
const homeworks = ref([]);
//从pinia获取课程ID
let store = useCounterStore();
const courseManageId = store.courseManageId;
const showBubble = ref(false)

// 获取作业列表
const fetchHomeworkList = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    const response = await gethomeworkService(courseManageId);
    console.log('后端返回作业:', response);

    if (!response || !response.data) {
      throw new Error('API返回数据格式错误');
    }

    const homeworkData = Array.isArray(response.data) ? response.data : [];
    console.log('API 返回的数据数组:', homeworkData);

    homeworks.value = homeworkData.map(item => {
      // 计算提交人数和总人数
      const submittedCount = Number(item.submitCount) || 0;  // 已提交人数
      const totalCount = Number(item.sum) || 0;  // 总人数

      // 计算平均分
      const totalScore = Array.isArray(item.scoreSet)
        ? item.scoreSet.reduce((acc, val) => acc + Number(val), 0)
        : 0;
      const averageScore = submittedCount > 0 
        ? Math.round(totalScore / submittedCount) 
        : 0;

      // 获取当前时间和截止时间
      const now = new Date();
      const dueTime = item.deadline ? new Date(item.deadline) : new Date();
      const status = now > dueTime ? '已截止' : '进行中';

      return {
        id: item.homeworkId || '',
        title: item.homeworkName || '',
        status: status,
        publishTime: item.createTime ? new Date(item.createTime) : new Date(),
        dueTime: item.deadline ? new Date(item.deadline) : new Date(),
        submittedCount: submittedCount,
        totalCount: totalCount,
        score: averageScore
      };
    });

    console.log('最终的作业数据:', homeworks.value);
  } catch (error) {
    console.error('获取作业列表错误:', error);
    ElMessage.error('获取作业列表失败');
  } finally {
    loading.close();
  }
};

// 点击卡片跳转
const handleCardClick = (homeworkId) => {
  console.log('handleCardClick被调用，homeworkId:', homeworkId);

  try {
    if (!homeworkId) {
      console.error('homeworkId is invalid:', homeworkId);
      ElMessage.error('无效的作业ID');
      return;
    }

    console.log('准备跳转到路径:', `/teacher/assignment/see_homework/${homeworkId}`);

    router.push({
      path: `/teacher/assignment/see_homework/${homeworkId}`,
      replace: true
    }).then(() => {
      console.log('路由跳转成功');
    }).catch(err => {
      console.error('路由跳转失败:', err);
      window.location.href = `/teacher/assignment/see_homework/${homeworkId}`;
    });
  } catch (error) {
    console.error('handleCardClick error:', error);
    ElMessage.error('页面跳转失败');
  }
};

// 格式化日期
const formatDate = (date) => {
  const options = { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false };
  return new Intl.DateTimeFormat('zh-CN', options).format(date);
};

// 页面加载时获取作业列表
onMounted(async () => {
  await fetchHomeworkList();
  const fromChat = route.query.fromChat
  if (fromChat) {
    showBubble.value = true
  }
});
</script>

<script>
export default {
  name: 'HomeworkCard'
};
</script>

<style scoped>
.header {
  color: white;
  padding: 10px;
  display: flex;
  align-items: center;
  background-color: #13227a;
  justify-content: space-between;
  /* 使内容两端对齐 */
}

.back-button {
  color: white;
  border: none;
  width: 25px;
  height: 25px;
}

.title {
  margin-left: 10px;
  /* 添加左边距 */
}

.header-right {
  display: flex;
  /* 使右侧内容为flex布局 */
}

.assign-button {
  background-color: #13227a;
  border: 1px solid white;
  color: white;
  width: 120px;
  height: 40px;
}

.homework-card-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  /* 强制三列布局 */
  gap: 20px;
  /* 统一的间距 */
  padding: 0 40px;
  margin-top: 20px;
}

.homework-card {
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  height: 220px;
  /* 删除width和flex相关属性，由grid控制宽度 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.homework-title {
  font-weight: bold;
  color: black;
  font-size: 20px;
}

.homework-status {
  color: gray;
  font-size: 14px;
  margin-top: 20px;
}

.homework-dates {
  color: gray;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  margin-top: 10px;
}

.homework-submission {
  color: darkgray;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: auto;
  margin-top: 40px;
  /* 增加距离 */
}

.submission-count,
.submission-score {
  text-align: center;
  margin-right: 15px;
}

.submission-number,
.score-number {
  font-size: 32px;
  /* 增大数字部分的大小 */
  color: darkgray;
}

.submission-label,
.score-label {
  font-size: 14px;
  color: darkgray;
}
</style>
